package com.misc.tunewsreader;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Pair;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;

public class SourceView extends Activity {
	private SectionListAdapter adapter;
	private static final int Menu_copy = Menu.FIRST + 1;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.source);

		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(this.getString(R.string.info));
		actionBar.addAction(new DoneAction(this, R.drawable.bar_accept));
		actionBar.setProgressBarVisibility(View.VISIBLE);

		final Bundle extras = getIntent().getExtras();

		Runnable loadThread = new Runnable() {
			@Override
			public void run() {
				loadInfo(extras.getString("post"));
				runOnUiThread(dispInfo);
			}
		};
		Thread thread = new Thread(null, loadThread, "LoadInfo");
		thread.start();
	}

	private void loadInfo(String post_id) {
		List<String> raw = NNTPClient.loadRawPostHeader(post_id);

		ArrayList<ListItem> items = new ArrayList<ListItem>();

		// parse header information
		String last_key = "", key = "", value = "", tmp;
		if (raw != null) {
			for (int i = 0; i < raw.size() - 1; i++) {
				Pair<String, String> data = NNTPArticleHeader.parseHeaderLine(
						raw.get(i), last_key);
				key = data.first;
				tmp = data.second;
				// quoted printable decoding of sender and subject
				if (key.equals("From") || key.equals("Subject")) {
					tmp = NNTPClient.decodeText(tmp);
				}

				if (key.equals(last_key))
					value += tmp;
				else
					value = tmp;

				if (!last_key.equals(key)) {
					items.add(new ListSection(key));
				} else {
					items.remove(items.size() - 1);
				}
				items.add(new ListEntry(value, value));

				last_key = key;
			}
		}

		adapter = new SectionListAdapter(this, items);
		adapter.useSmallLayout(true);
	}

	private Runnable dispInfo = new Runnable() {
		@Override
		public void run() {
			ListView post_info = (ListView) findViewById(R.id.post_info);

			// fill listview
			post_info.setAdapter(adapter);
			registerForContextMenu(post_info);

			// hide progress indicator
			((ActionBar) findViewById(R.id.actionbar))
					.setProgressBarVisibility(View.GONE);
		}
	};

	public static class DoneAction extends AbstractAction {
		private Context mContext;

		public DoneAction(Context context, int drawable) {
			super(drawable);
			mContext = context;
		}

		@Override
		public void performAction(View view) {
			((SourceView) mContext).finish();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.post_info) {
			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			menu.setHeaderTitle(((ListSection) adapter
					.getItem(info.position - 1)).getTitle());
			menu.add(Menu.NONE, Menu_copy, 0, getApplicationContext()
					.getString(R.string.copy_clipboard));
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		String data = ((ListEntry) adapter.getItem(info.position)).full_name;

		copyToClipboard(data);
		return true;
	}

	@SuppressLint("NewApi") @SuppressWarnings("deprecation")
	private void copyToClipboard(String str) {
		int sdk = android.os.Build.VERSION.SDK_INT;
		if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
			android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			clipboard.setText(str);
		} else {
			android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
			android.content.ClipData clip = android.content.ClipData
					.newPlainText(str, str);
			clipboard.setPrimaryClip(clip);
		}
	}

}
